package com.lee.common.network

import com.lee.common.BuildConfig
import com.lee.common.utils.accessToken
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import timber.log.Timber
import java.util.concurrent.TimeUnit

object ApiFactory {
    inline fun <reified T> create(
        baseUrl: String,
        saveCookie: Boolean,
        noinline creator: (Int, String, Any?) -> Any
    ): T {
        val clientBuilder = OkHttpClient.Builder()
            .connectTimeout(6000, TimeUnit.SECONDS)
            .readTimeout(1, TimeUnit.MINUTES)
            .writeTimeout(1, TimeUnit.MINUTES)
        if (BuildConfig.DEBUG) {
            val loggingInterceptor =  HttpLoggingInterceptor { message ->
                if (BuildConfig.DEBUG) {
                    Timber.e("OkHttp====Message:$message")
                }
            }
            loggingInterceptor.level = HttpLoggingInterceptor.Level.BODY
            clientBuilder.addInterceptor(loggingInterceptor)
        }
        clientBuilder.addInterceptor(Interceptor { chain ->
            val request = chain.request()
                .newBuilder()
                .addHeader("token", accessToken)
                .build()
            chain.proceed(request)
        })
        return Retrofit.Builder()
            .baseUrl(baseUrl)
            .client(clientBuilder.build())
            .addConverterFactory(CustomGsonConverterFactory.create())
            .addCallAdapterFactory(LiveDataCallAdapterFactory(creator))
            .build()
            .create(T::class.java)
    }
}